package com.youxin.admin.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youxin.admin.user.entity.req.AgentSearchReq;
import com.youxin.admin.user.mapper.AgentInfoMapper;
import com.youxin.admin.user.model.AgentInfo;
import com.youxin.admin.user.service.AgentService;
import com.youxin.base.TPage;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * description: AgentInfoServiceImpl <br>
 * date: 2020/3/4 16:37 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class AgentInfoServiceImpl extends ServiceImpl<AgentInfoMapper, AgentInfo> implements AgentService {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public TPage<AgentInfo> pageAgents(AgentSearchReq agentSearch) {
        LambdaQueryWrapper<AgentInfo> queryWrapper = new LambdaQueryWrapper<AgentInfo>();
        if(!StringUtils.isEmpty(agentSearch.getAgentNo())) {
            queryWrapper.eq(AgentInfo::getAgentNo, agentSearch.getAgentNo());
        }
        IPage<AgentInfo> page = this.baseMapper.selectPage(new Page<>(agentSearch.getCurrentPage(),agentSearch.getShowCount()),queryWrapper);
        return TPage.page(page.getRecords(),page.getTotal());

    }

    @Override
    public void saveAgent(AgentInfo agentInfo) {
        if(agentInfo.getId() == null){
            agentInfo.setAgentNo(generateAgentNo());
            this.baseMapper.insert(agentInfo);
        }else{
            this.baseMapper.updateById(agentInfo);
        }
    }

    public String generateAgentNo() {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong("com.guoliao.userpermission.no.generator", redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        String seq = String.format("%04d", increment + 1L);
        System.out.println(seq);
        if (null == increment || increment == 0L) {
            long liveTime = Duration.between(LocalDateTime.now(), LocalDate.now().plusMonths(1L).atStartOfDay()).getSeconds();
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);
        }

        String userNo = "A" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")).substring(0, 4) + seq;
        return userNo;
    }
}
